<?php

class User extends CActiveRecord
{
    CONST NAME_MIN_LEN = 2;
    CONST NAME_MAX_LEN = 12;
    CONST PASSWORD_MIN_LEN = 6;
    CONST PASSWORD_MAX_LEN = 20;    
    CONST EMAIL_MIN_LEN = 6;
    CONST EMAIL_MAX_LEN = 32;

    public static $genderLabels=array('-1'=>'未填写','0'=>'男', 1=>'女');
    public static $autoLoadAttributes=array('id','name');
    
    private $_image;
    private $_saveAttributes;
     
     
    /********************************************************************
    *  Below are class functions
    *  WARNING: You should only use these functions to manipulate 
    *           the object instead of AR functions.
    *********************************************************************/
    
    public static function loadObjectById($id,$attributes='*')
    {
        if(is_array($attributes)){
            $attributes=array_unique(array_merge($attributes,self::$autoLoadAttributes));
        }
        return self::loadObject(array(
            'condition'=>'id=:id',
            'params'=>array(':id'=>$id),
            'select'=>$attributes,
        ));
    }
    
    public static function loadObjectByName($name,$attributes='*')
    {
        if(is_array($attributes)){
            $attributes=array_unique(array_merge($attributes,self::$autoLoadAttributes));
        }
        return self::loadObject(array(
            'condition'=>'name=:name',
            'params'=>array(':name'=>$name),
            'select'=>$attributes,
        ));
    }
    
    public static function loadObjectByEmail($email,$attributes='*')
    {
        if(is_array($attributes)){
            $attributes=array_unique(array_merge($attributes,self::$autoLoadAttributes));
        }
        return self::loadObject(array(
            'condition'=>'email=:email', 
            'params'=>array(':email'=>$email),
            'select'=>$attributes,
        ));
    }

    public static function loadObject($criteria=array())
    {
        $criteria['limit']=1;                                 
        return array_shift(self::loadObjects($criteria));
    }
    
    public static function loadObjects($criteria=array())
    {
        return self::model()->findAll($criteria);
    }
    
    public static function saveObject(&$object, $attributes=null)
    {
        if(is_array($attributes))
            $object->_saveAttributes=array_flip($attributes);
        else
            $object->_saveAttributes=$attributes;

        if($object->getIsNewRecord()){
            $ret=self::createObject($object, $attributes);
        }
        else {
            $ret=$object->save(true, $attributes);
        }

        unset($object->_saveAttributes);
        return $ret;
    }

    public static function deleteObject(&$object)
    {
        return $object->delete();
    }
        
    protected static function createObject(&$object, $attributes=null)
    {
        $transaction=Yii::app()->db->beginTransaction();
        try {
            if(!$object->save(true, $attributes))
                return false;

            $kitchen=new Kitchen;
            $kitchen->id=$object->id;
            $kitchen->userName=$object->name;
            $kitchen->title=sprintf("%s的厨房", $object->name);

            if(!$kitchen->save()) 
                throw new CException('create kitchen failed');
                
            $transaction->commit();
            return true;
        }
        catch(Exception $e){
            $transaction->rollBack();
            if(strstr($e->getMessage(),'1062 Duplicate entry')===false) {
                throw $e;
            }
            if(strstr($e->getMessage(),'for key 2')!==false) {
                $object->addError('name', $object->getAttributeLabel('name').$object->name.' 已存在');
            }
            elseif(strstr($e->getMessage(),'for key 3')!==false) {
                $object->addError('email', $object->getAttributeLabel('email').$object->email.' 已存在');
            }
            return false;
        }
    }    
    
    /********************************************************************
    *  Below are object & AR required functions
    *********************************************************************/

    public static function model($className=__CLASS__)
    {
        return parent::model($className);
    }
    
	public function tableName()
	{
		return 'User';
	}

	public function rules()
	{
		return array(
            array('name,password','required','on'=>'create'),
            array('name','WStringValidator','min'=>self::NAME_MIN_LEN, 'max'=>self::NAME_MAX_LEN),
            array('name', 'validateName'),
            array('password','length','min'=>self::PASSWORD_MIN_LEN,'max'=>self::PASSWORD_MAX_LEN),
            array('email','length', 'min'=>self::EMAIL_MIN_LEN, 'max'=>self::EMAIL_MAX_LEN),            
            array('email','email'),
            array('gender','in','range'=>array_keys(self::$genderLabels)),
		);
	}

    public function validateName($object,$attribute)
    {
        if(!$this->hasErrors())
        {
            for($i=0;$i<$len;++$i) {
                if($this->name[$i]===' '){
                    $this->addError('name', $this->getAttributeLabel('name').' 中不能包含空格');
                    return false;                    
                }
                if($this->name[$i]==='@'){
                    $this->addError('name', $this->getAttributeLabel('name').' 中不能包含@');
                    return false;                                
                }        
            }
            return true;
        }
    }

	public function attributeLabels()
	{
        return array(
            'id' => '帐号',
            'name' => '用户名',
            'description'=>'自我描述',
            'email' => '电子邮件',
            'password' => '密码',
            'gender'=>'性别',
            'image'=>'图片',
            'registerIp'=>'注册IP',
            'registerTime'=>'注册时间',
            'lastLoginIp'=>'最近一次登录IP',
            'lastLoginTime'=>'最近一次登录时间',
        );
	}
    
    protected function isSaveAttribute($name)
    {
        if(is_array($this->_saveAttributes))
            return array_key_exists($name,$this->_saveAttributes);
        return true;
    }

    protected function beforeSave()
    {
        if($this->isSaveAttribute('image')){
            $this->_image = $this->image;
            $this->image = json_encode($this->image);
        }
        if($this->isSaveAttribute('password')){
            $this->password=md5($this->password);
        }
        return true;
    }

    protected function afterSave()
    {
        if($this->isSaveAttribute('image')){
            $this->image = $this->_image;
            $this->_image = null;
        }
    }

    protected function afterFind()
    {
        if(is_string($this->image)){    
            $this->image = json_decode($this->image);
        }
    }        
}